import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hilbert

# 创建 x 值的数组
x = np.linspace(0, 2 * np.pi, 1000)
signal = np.sin(x)

# 计算希尔伯特变换
analytic_signal = hilbert(signal)
hilbert_transform = np.imag(analytic_signal)

#计算原信号与虚部移相后的信号的均方根。
envelope = np.sqrt(hilbert_transform*hilbert_transform +signal*signal)


# 生成复信号
complex_signal = signal + 1j * hilbert_transform

# 计算相位
phase = np.angle(complex_signal)

# 移相
phase_shift = np.pi / 4  # 例如，移相 45 度
shifted_complex_signal = np.abs(complex_signal) * np.exp(1j * (phase + phase_shift))

# 提取移相后的实部
shifted_real_signal = np.real(shifted_complex_signal)

# 绘制结果
plt.figure(figsize=(12, 8))
plt.subplot(3, 1, 1)
plt.plot(x, signal, label='Original Signal')
plt.title('Original Signal')
plt.grid(True)

plt.subplot(3, 1, 2)
plt.plot(x, hilbert_transform, label='Hilbert Transform')
plt.title('Hilbert Transform')
plt.grid(True)

plt.subplot(3, 1, 3)
plt.plot(x, envelope , label='envelope Signal', linestyle='--')
plt.title('Envelope  Signal')
plt.grid(True)

plt.tight_layout()
plt.show()